package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Item;

import dao.ItemDao;

import util.MyJson;
import util.ParameterCheck;
import util.TagsBinarySort;

/**
 * Servlet implementation class Serach
 */
public class Search extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Search() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		int index=ParameterCheck.intDefault(request.getParameter("index"));
		int totalPage=ParameterCheck.intDefault(request.getParameter("pagecount"));
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw = response.getWriter();
		try{
		String tags=ParameterCheck.stringDefault(request.getParameter("word"));
//		System.out.println(tags);
		if("".equals(tags)){
			pw.write(MyJson.toJson("fail", "请输入您要查询的信息"));
		}
		else{
			
			ItemDao itemdao=new ItemDao();
			List<String> taglist=TagsBinarySort.GetSortedList(tags.split(" "));
//			System.out.println("tags:"+tags);
//			System.out.println("taglist:"+taglist);
			List<Integer> totalcount=new ArrayList<Integer>();
			List<Item> items=itemdao.findItems(taglist,index,totalcount);
			totalPage=totalcount.get(0);
			StringBuilder build=new StringBuilder();
			build.append("{items:[");
			for(int i=0;i<items.size();i++){
				Item item=items.get(i);
			 	build.append("{\"name\":\"").append(item.getName()).append("\",\"code\":\"").append(item.getCode()).append("\",\"img\":\"").append(item.getImg()).append("\",\"tags\":\"").append(item.getTags())
			 	.append("\",\"match\":\"").append(item.getMatchedTags()).append("\",\"comment\":\"").append(item.getComment_count()).append("\",\"vote\":\"").append(item.getHot()).append("\"},");
			}	
			build.append("],totalPage:"+totalPage+"}");
			pw.write(build.toString());
		}		
		}catch(Exception e){
			e.printStackTrace();
			pw.write("{items:[],totalPage:"+totalPage+"}");
		}
		pw.flush();
		pw.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
